from django.shortcuts import render,HttpResponse,redirect
from django import forms
from ..models import Admin
from ..utlis.encrypt import md5

#导入验证码插件
from ..utlis.yanzhengm import check_code
from io import BytesIO

class LoginForm(forms.Form):
    username=forms.CharField(
        label="用户名",
        widget=forms.TextInput(attrs={"class":"form-control"}),
        #required=True,
    )
    password = forms.CharField(
        label="密码",
        widget=forms.PasswordInput(attrs={"class": "form-control"}),
        #required=True,
    )

    code = forms.CharField(
        label="验证码",
        widget=forms.TextInput,
        #required=True
    )

    def clean_password(self):
        pwd=self.cleaned_data.get("password")
        return md5(pwd)

"""登录"""
def login(request):
    if request.method == "GET":
        form = LoginForm()          #实例化form表单
        return render(request,"login.html",{"form":form})

    form = LoginForm(data=request.POST)
    if form.is_valid():
        # is_valid自动判断用户名和密码是否正确
        # form.cleaned_data 可以捕获到登录的用户名和密码
        # print(form.cleaned_data)
        """
        is_valid 背后运行逻辑：
        1.LoginForm实例化：
            self.fields={
                'user':正则表达式,
                'pwd':正则表达式
            }
        2.循环self.fields
            flag = True
            errors
            cleaned_data
            for k,v in self.fields.items():
                1.user 正则表达式
                input_value = request.POST.get(k)
                正则表达式和input_value
                flag = False
            return flag
        """

        #验证码校验
        user_input_code = form.cleaned_data.pop('code')
        code = request.session.get('image_code',"")
        if code.upper() != user_input_code.upper():
            form.add_error("code", "验证码错误")
            return render(request, "login.html", {"form": form})


        admin_object=Admin.objects.filter(**form.cleaned_data).first()
        if not admin_object:
            form.add_error("password","用户名或密码错误")
            return render(request,"login.html",{"form":form})

        #通过session实现用户登录；用户名和密码正确
        # 1、网站生成随机字符串
        # 2、通过cookie发送给客户端
        # 3、服务端保存(保存在Django数据库中，django_session )
        #下面一行代码实现1 2 3这三个步骤的功能柜
        request.session["info"]={'id':admin_object.id,'name':admin_object.username}

        # 1、获取客户端cookie中的随机字符串
        # 2、去session中查找有没有随机字符串
        # 3、去session对应key的value中查看是否有username
        # request.seesion.get('username'）

        #session可以保存7天
        request.session.set_expiry(60 * 60 * 24 * 7)

        return redirect("/devices/")
    return render(request,"login.html",{"form":form})


""" 注销 """
def logout(request):
    request.session.clear()
    return redirect("/login/")


"""生成图片验证码"""
def yzm_code(request):

    #调用pillow函数，生成函数
    img,code_string = check_code()

    #写入到自己的session中（以便于后续获取验证码再进行校验）
    request.session['image_code'] = code_string
    #给session设置60s超时
    request.session.set_expiry(60)

    stream = BytesIO()
    img.save(stream,'png')
    stream.getvalue()

    return HttpResponse(stream.getvalue())